package cn.com.zsw.gblog.config.security;

import cn.com.zsw.gblog.config.cache.RedisCache;
import cn.com.zsw.gblog.constants.SysConstants;
import cn.com.zsw.gblog.modules.gblog.enums.ResponseCode;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author ：shiwangzhou
 * @Date ：Created in 2020-09-16 16:37
 * @Description：
 */
@Component
public class LogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {
    @Autowired
    RedisCache redisCache;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String header = request.getHeader("X-Token");
        if (StringUtils.isEmpty(header)) {
            header = request.getParameter("X-Token");
        }
        redisCache.deleteObject(SysConstants.REDIS_JWT_TOKEN_ID + header);
//        Object principal = authentication.getPrincipal();
        String msg = String.format("用户注销成功");
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", ResponseCode.SUCCESS.getCode());
        jsonObject.put("msg", msg);
        writer.write(jsonObject.toJSONString());
    }
}
